<?php
// ----------------------------------------------------------------------
// pn-commerce Shopping Cart Solution for PostNuke
// http://pncommerce.de
// http://www.sourceforge.net/projects/pn-commerce/
//
// It is based on PostKart 0.701QA from
//			Destin LeBlanc [ postkart@zenflesh.com ]
// ----------------------------------------------------------------------
// Source file:  $Source: /cvsroot/pn-commerce/pn-commerce/pnpm2checkoutapi.php,v $
//
// Last changes from:  $Author: landseer $
//
// Revision:           $Revision: 1.16 $
//
// Date of revision    $Date: 2004/09/12 11:17:13 $
//  
// ----------------------------------------------------------------------
// LICENSE
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License (GPL)
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// To read the license please visit http://www.gnu.org/copyleft/gpl.html
// ----------------------------------------------------------------------

require_once("modules/pncommerce/common.php");

/**
 * load the config array and return it
 * no arguments needed
 */
function pncommerce_pm2checkoutapi_getConfig ()
{
    $data=pnModGetVar ( 'pncommerce', 'pm2checkoutData');
    if( isset( $data ) )
    {
        return unserialize( $data );
    }
    return false;
}

/**
 * save the config array
 * @param $args array of config values
 */
function pncommerce_pm2checkoutapi_setConfig ($args)
{
    pnModSetVar ( 'pncommerce', 'pm2checkoutData', serialize( $args ) );
}

/**
 * This function is used during the checkout process
 * it's called after the checkout where the user agrees to
 * buy the items, so you can do the rest here to finish the
 * payment process if possible. 
 * don't forget to bypass all important informations 
 * like ON,KID,maxStep
 * it's important when the user jumps back to earlier steps
 *
 * @param $args['KID'] string CustomerID
 * @param $args['ON']  string order number
 */
function pncommerce_pm2checkoutapi_processpayment ($args)
{ 
    // special for 2checkout.com: We display a button which leads to the 2checkout.com website
    // We pass all information we have so far. After poressing the payment, 2checkout.com
    // will then redirect to processshippingfinal
    extract( $args );

	if (!pnModAPILoad('pncommerce', 'user'))
	{
	    return false;
	}

	$order = pnModAPIFunc( 'pncommerce', 'user', 'getOrder',
	                       array( 'ON' => $ON ) );
    if( $order <> false )
    {
    	$config = pncommerce_pm2checkoutapi_getConfig();

        $smarty = new pnRender();
        $smarty->caching = false;
        $smarty->assign( 'config', $config );
        
        if( $config['Testmode'] == 'on' )
        {
            $test_2co  = "Y";
            $test_auth = "TRUE";
        }
        else
        {
            $test_2co  = "N";
            $test_auth = "FALSE";
        }
        $smarty->assign( 'test_2co', $test_2co );
        $smarty->assign( 'test_auth', $test_auth );
        $smarty->assign( 'KID', $KID );
        $smarty->assign( 'ON', $ON );
        $smarty->assign( 'Amount', ereg_replace( ",", ".", $order['CartData']['Total'] ) );
        $smarty->assign( 'order', $order );
        
        if( $config['Mode'] == 1 )
        {
            // interface is 2checkout.com
            return $smarty->fetch( 'pncommerce_2checkoutapi_2checkoutcom.html' );
        }
        else
        {
            // interface is authorize.net
            return $smarty->fetch( 'pncommerce_2checkoutapi_authorizenet.html' );
        }   
    }
    else
    {
		return howerrorpage( _PNC_FAILEDTOGETORDERDATA, __FILE__, __LINE__ );
    }
}

/**
 * This function is used during the checkout process
 * you can let the user provide special information
 * you need for further processing
 * when you don't need any info just redirect the user to
 * getshippingmethod in the pnuser.php
 * don't forget to bypass all important informations 
 * like BPM,BSM,KID,maxStep
 * it's important when the user jumps back to earlier steps
 * @param $args['KID'] string CustomerID
 * @param $args['BPM'] string selected Paymethod
 * @param $args['BSM'] string selected Shippingmethod
 * @param $args['maxStep'] int highest Step the user reached in this checkout process
 */
function pncommerce_pm2checkoutapi_getdata ($args)
{
    // we do not need to ask for additional data for 2checkout.com
	pnRedirect( pnModURL( 'pncommerce', 'user', 'getshippingmethod', $args ) );
	return true;
}

/**
 * This function is used during the checkout process
 * you can save the provide information here
 * getshippingmethod in the pnuser.php
 * don't forget to bypass all important informations 
 * like BPM,BSM,KID,maxStep
 * it's important when the user jumps back to earlier steps
 * 
 * It's important to redirect to getshippingmethod if everything was ok here
 *
 * @param $args['KID'] string CustomerID
 * @param $args['BPM'] string selected Paymethod
 * @param $args['BSM'] string selected Shippingmethod
 * @param $args['maxStep'] int highest Step the user reached in this checkout process
 */
function pncommerce_pm2checkoutapi_getdataresponse($args)
{
    //we don't need to do here something because this function will never be called in this paymethod
}

function pncommerce_pm2checkoutapi_userinsert ($args)
{
    // not used in 2checkout
}

function pncommerce_pm2checkoutapi_order($args)
{
    // not used in 2checkout
}

function pncommerce_pm2checkoutapi_configintro ($args)
{
	$Mode = pnVarCleanFromInput( 'Mode' );
    
	if (!pnModAPILoad( 'pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
    }
	
	if (pnSecAuthAction(0, '::', '::', ACCESS_ADMIN))
	{
	    switch ($Mode)
	    {
	    case 'install':
	    	$default=array('PMCalcFunc'=>'PMCFlat',
	    		           'PMCFlatPrice' => '0',
	    		           'Mode' => 0,
	    		           'Testmode' => 'on' );
	    	pncommerce_pm2checkoutapi_setConfig($default);
	    	pnModSetVar ('pncommerce', 'pm2checkout', 'on');
	    	break;
	    case 'remove':
            pncommerce_pm2checkoutapi_quietremove();
	    	break;
	    case 'activate':
	    	pnModSetVar ('pncommerce', 'pm2checkout', 'on');
	    	break;
	    case 'deactivate':
	    	pnModSetVar ('pncommerce', 'pm2checkout', 'off');
	    	break;
	    default:
	    	break;
	    }
	    pnRedirect( pnModAPIFunc('pncommerce','user','pncModURL',
	    						array('Module'=>'pncommerce', 'Section'=> 'admin', 'Function'=>'paymethodconfig')));
        return true;
	}
	else
	{
		return showerrorpage( _PNC_NOAUTH, __FILE__, __LINE__ );
	}
}

function pncommerce_pm2checkoutapi_showoption($args)
{
	extract ($args);
	$temp ="<input type='radio' name='PayMethod' value='pm2checkout'";
	if ( $BPM == 'pm2checkout' )
	{
		$temp .= " checked ";
	}
	$temp .= ">"._PNC_2CHECKOUTORDER;
	$config = pncommerce_pm2checkoutapi_getConfig();
	if( ($config['Testmode'] == 'on') )
	{
	    $temp.= " -- "._PNC_TESTMODEACTIVE."<br>";
	}
	else
	{
	    $temp .= "&nbsp;<img src='modules/pncommerce/pnimages/ccards.gif' border='0' alt=''><br>";
	}
	return $temp;
}

function pncommerce_pm2checkoutapi_info ()
{
    return _PNC_2CHECKOUTORDER;
}

function pncommerce_pm2checkoutapi_footermsg ($args)
{
	extract ($args);
	$temp = ""._PNC_2CHECKOUTORDER."<br>"._PNC_WEWILLSHIPUPONAPPROVAL."<br>";
	return $temp;
}

function pncommerce_pm2checkoutapi_quietremove ()
{
	pnModDelVar ('pncommerce', 'pm2checkout');
	pnModDelVar ('pncommerce', 'pm2checkoutData');
}

/**
 * This function is used during the checkout process
 * You can calculate a fee for the selected paymethod here
 *
 * @param $args['SubTotal'] Double the total costs with shipping included
 * @return double 
 * @returns the fee for this paymethod or 0 when this paymethod is free of charge
 */
function pncommerce_pm2checkoutapi_getPaymethodTotal($args)
{
	if (!pnModAPILoad( 'pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnadminapi", __FILE__, __LINE__);
    }
	$config=pncommerce_pm2checkoutapi_getConfig();
	//add value to array to make the function able to calculate the fee
	$config['Value']=$args['SubTotal'];
	return pnModAPIFunc( 'pncommerce', 'user', 'getPMCalcValue', $config);
}

/**
 * Asks for special data for this paymethod, for example minimum fee or default fee, ...
 * Account numbers, ...
 * ****
 * You have to redirect to 'paymethodconfig' when you're done
 * ****
 * @return String 
 * @returns the config page for this paymethod
 */
function pncommerce_pm2checkoutapi_config()
{
	if (!pnModAPILoad( 'pncommerce', 'admin'))
    {
        return showerrorpage("unable to load pnadminapi", __FILE__, __LINE__);
    }
	if (!pnModAPILoad( 'pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnuserapi", __FILE__, __LINE__);
    }
    
    $Submit = pnVarCleanFromInput( 'Submit' );

	if (pnSecAuthAction(0, '::', '::', ACCESS_ADMIN))
	{
    	$smarty = new pnRender();
        $smarty->caching = false;
    	$config=pncommerce_pm2checkoutapi_getConfig();
        
        if( !$Submit )
        {
    	    if( $config['Testmode'] == "on" )
    	    {
    	        $testmode = "checked";
    	    }
    	    $mode[$config['Mode']] = " selected";
    	    
            $smarty->assign( 'config', $config );
            $smarty->assign( 'testmode', $testmode );
            $smarty->assign( 'mode', $mode );
		    return $smarty->fetch( 'pncommerce_2checkoutapi_configuration.html' );

        } // $Submit is set
        else
        {
    
    $authid = pnVarCleanFromInput( 'authid' ); 
    if( !pnSecConfirmAuthKey( $authid ) ) 
    { 
        return showerrorpage( _PNC_BADAUTHKEY, __FILE__, __LINE__ ); 
    }     
    
		    $storage=array();
		    $storage['PMCalcFunc'] = pnVarCleanFromInput('PMCalcFunc');
		    $storage=pnModAPIFunc( 'pncommerce','user','gatherPMCalcData',$storage);
		    $storage['ID']       = pnVarCleanFromInput( 'coID' );
		    $storage['Testmode'] = pnVarCleanFromInput( 'coTestmode' );
		    $storage['Mode']     = pnVarCleanFromInput( 'coMode' );
		    pncommerce_pm2checkoutapi_setConfig($storage);

		    $url = pnModAPIFunc( 'pncommerce','user','pncModURL',
		    					  array('Module'=>'pncommerce', 'Section'=> 'admin', 'Function'=>'paymethodconfig'));
		    pnRedirect($url);
		    return true; 
        }
	}
	return false;
}

/*
 * onlinepayment
 * This is the function that will be alled from 2checkout.com after processing
 * the payment. It reads the necessary information from the fields 'cart_order_id' or
 * 'x_cust_id' which is in the format 'ON@KID'
 */
function pncommerce_pm2checkoutapi_onlinepayment()
{
   	$config=pncommerce_pm2checkoutapi_getConfig();
    if( $config['Mode'] == 1 )
    {
        // 2checkout.com
        $return = pnVarCleanFromInput( 'cart_order_id' );
    }
    elseif( $config['Mode'] == 2 )
    {
        // authorize.net
        $return  = pnVarCleanFromInput( 'x_cust_id' );
    }
    $ret = explode( "@", $return );

	if (!pnModAPILoad( 'pncommerce', 'user'))
    {
        return showerrorpage("unable to load pnadminapi", __FILE__, __LINE__);
    }

	pnRedirect( pnModURL( 'pncommerce', 'user', 'processshippingfinal',
	                      array( 'ON'  => $ret[0],
	                             'KID' => $ret[1] ) ) );
	return true;
} 
   
?>
